package top.jandmla.excel.service.serviceImpl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import top.jandmla.excel.bean.Name;
import top.jandmla.excel.bean.Test;
import top.jandmla.excel.pojo.DownloadFileDTO;
import top.jandmla.excel.service.FileDownLoadService;
import top.jandmla.excel.service.NameService;
import top.jandmla.excel.service.TestService;
import top.jandmla.excel.util.Backups;
import top.jandmla.excel.util.FileDownLoad;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class FileDownLoadServiceImpl implements FileDownLoadService {

    @Autowired
    private NameService nameService;

    @Autowired
    private TestService testService;

    @Override
    public void downLoadFile(DownloadFileDTO dto, HttpServletResponse rse) {

        List<List<Test>> testList = new ArrayList<>();

        QueryWrapper<Name> qn = new QueryWrapper<>();
        boolean qnb = false;

        QueryWrapper<Test> qt = new QueryWrapper<>();
        Name nQuery = dto.getName();

        if (!StringUtils.isEmpty(nQuery.getId())) {
            qnb = true;
            qn.eq("id", nQuery.getId());
        }
        if (!StringUtils.isEmpty(nQuery.getName())) {
            qnb = true;
            qn.eq("name", nQuery.getName());
        }

        //如果name存在条件
        if (qnb) {
            List<Name> names = nameService.list(qn);
            for (Name name : names) {
                QueryWrapper<Test> qw = new QueryWrapper<>();
                qw.eq("nameid", name.getId());
                testList.add(testService.list(qw));
            }
        }

        Test tQuery = dto.getTest();
        if (!StringUtils.isEmpty(tQuery.getNameid())) {
            qt.eq("nameid", tQuery.getNameid());
        }

        if (!StringUtils.isEmpty(tQuery.getId())) {
            qt.eq("id", tQuery.getId());
        }

        if (!StringUtils.isEmpty(tQuery.getName())) {
            qt.like("name", tQuery.getName());
        }

        if (!StringUtils.isEmpty(tQuery.getPhone())) {
            qt.eq("phone", tQuery.getPhone());
        }

        if (!StringUtils.isEmpty(tQuery.getEmail())) {
            qt.eq("email", tQuery.getEmail());
        }

        testList.add(testService.list(qt));
        String file = Backups.writeExcel(testList, String.valueOf(new Date().getTime()));
        FileDownLoad.download(file, rse);
        FileUtils.deleteQuietly(FileUtils.getFile(file));
    }
}
